﻿using System;
using Windows.Storage.Pickers;
using Windows.UI.Xaml.Input;
using LinkPad.Shapes;

namespace LinkPad.Handlers
{
    class ImageAdder : CanvasActionHandler
    {
        #region Constructors
        
        public ImageAdder(ShapeManager shapeManager) : base(shapeManager)
        {
        }

        #endregion

        #region Methods

        protected override async void HandleCanvasDoubleTapped(object sender, DoubleTappedRoutedEventArgs e)
        {
            var position = e.GetPosition(MyCanvas);

            var filePicker = new FileOpenPicker
            {
                SuggestedStartLocation = PickerLocationId.PicturesLibrary
            };
            filePicker.FileTypeFilter.Add(".bmp");
            filePicker.FileTypeFilter.Add(".gif");
            filePicker.FileTypeFilter.Add(".jpg");
            filePicker.FileTypeFilter.Add(".png");

            var file = await filePicker.PickSingleFileAsync();
            if (file != null)
            {
                using (var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                {
                    var image = new ManagedImage(ShapeManager)
                    {
                        X = position.X,
                        Y = position.Y
                    };
                    image.LoadFromImageSource(fileStream);
                    ShapeManager.AddShape(image);
                }
            }

            e.Handled = true;

            base.HandleCanvasDoubleTapped(sender, e);
        }

        #endregion
    }
}
